/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.service.broadcast;

import com.thienloc.omap.util.Constant;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Properties;

/**
 *
 * @author GiangLT
 */
public class BroadcastService {

    private Socket socket;

    public Socket connect(String host, int port) throws UnknownHostException, IOException {
        this.socket = new Socket(host, port);
        return socket;
    }

    public Socket connect() throws UnknownHostException, IOException {
        Properties properties = new Properties();
        File file = new File(Constant.CONFIG_FOLDER + Constant.CONFIG_FILE_NAME);
        properties.load(new FileReader(file));
        String host = properties.getProperty("broadcast.server.host", "localhost");
        int port = Integer.parseInt(properties.getProperty("broadcast.server.port", "15000"));
        return connect(host, port);
    }

    public void disconnect(Socket socket) throws IOException {
        if (socket != null && !socket.isClosed()) {
            socket.close();
        }
    }

    public void disconnect() throws IOException {
        disconnect(socket);
    }
    
    public void send(Socket socket, String message) throws IOException {
        socket.getOutputStream().write(message.getBytes());
    }
    
    public void send(String message) throws IOException {
        send(socket, message);
    }
}
